const WebSocket = require('ws');
const axios = require('axios');

let WS_URL = 'wss://stream.binance.com:9443/ws/btcusdt@kline_';
const timeFrames = {
  '1m': WS_URL + '1m',
  '5m': WS_URL + '5m',
  '30m': WS_URL + '30m',
  '1h': WS_URL + '1h',
  '1d': WS_URL + '1d',
  '1M': WS_URL + '1M'
}



class BinanceWs {
  constructor(timeFrames, postIndex) {
    this.postIndex = postIndex
    this.symbol = 'BTCUSDT'
    this.postUrl = 'http://rest.test/api/ws/sockets/one'
    this.reload = 'http://rest.test/api/rest/history'
    this.timeFrames = timeFrames
    // 获取历史数据
    this.getReload()
  }
  Open() {
    let ws = new WebSocket(this.timeFrames)
    ws.on('open', () => {
      console.log('open');
    });

    ws.on('message', (data) => {
      // console.log(data)
      console.log(this.postIndex)
      data = JSON.parse(data);
      axios.post(this.postUrl, {
        k: data.k
      }).then(res => {
        console.log(res)
      }).catch(function (error) {
        console.log(error);
      });
    });

    ws.on('error', (err) => {
      console.log(`${this.postIndex}连接错误`, err);
    })

    ws.on('close', (e) => {
      console.log(`${this.index}连接关闭`, e.code, e.reason);
      this.getReload()
    });
  }
  getReload() {
    axios.get(this.reload, {
      params: {
        size: 100,
        symbol: this.symbol,
        period: this.postIndex
      }
    }).then(res => {
      console.log(res)
      if (res.status === 200) {
        this.Open()
      }
    }).catch((error) => {
      console.log(error);
      return this.getReload()
    });
  }

}

let ws_1m = new BinanceWs(timeFrames['1m'], "1m")
let ws_5m = new BinanceWs(timeFrames['5m'], "5m")
let ws_30m = new BinanceWs(timeFrames['30m'], "30m")
let ws_1h = new BinanceWs(timeFrames['1h'], "1h")
let ws_1d = new BinanceWs(timeFrames['1d'], "1d")
let ws_1M = new BinanceWs(timeFrames['1M'], "1M")
